import { asyncRoutes, constantRoutes } from '@/router'
import sysMenuApi from "@/api/system/sysMenu";
/* Layout */
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归组装路由
 * 主要是把后台返回的component处理成component: () => import('@/views/dashboard/index'),
 * @param routes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if(tmp.component){
      //Layout
      if(tmp.component === "Layout"){
        tmp.component=Layout
      }else{
        tmp.component=loadView(route.component)
      }
    }
    if(tmp.children&&tmp.children[0]){
      tmp.children=filterAsyncRoutes(tmp.children)
    }
    res.push(tmp)
  })
  return res
}
//在我们接口提供的数据中，并不是完整的引入了路径 ，如果提供了@会报 因上，我们需要手动处理
export const loadView =(view)=>{
  return (resolve)=>require([`@/views/${view}`],resolve)
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      sysMenuApi.getRouters().then(res=>{
        const accessedRoutes=filterAsyncRoutes(res.data);
        console.log(accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
